package com.yami.shop.multishop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.ShopDivisionReceiver;
import com.yami.shop.bean.model.ShopDivisionReceiverGroup;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ShopDivisionReceiverGroupService;
import com.yami.shop.service.ShopDivisionReceiverService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@AllArgsConstructor
@RequestMapping("/shop/divisionReceiverGroup")
@Tag(name = "店铺分账管理（账号组）接口")
public class ShopDivisionReceiverGroupController {

    private final ShopDivisionReceiverGroupService shopDivisionReceiverGroupService;

    private final ShopDivisionReceiverService shopDivisionReceiverService;

    @GetMapping("/page")
    @Operation(summary = "分页查询店铺分账管理（账号组）", description = "分页查询店铺分账管理（账号组）")
    public ServerResponseEntity<IPage<ShopDivisionReceiverGroup>> getShopWalletLogPage(PageParam<ShopDivisionReceiverGroup> page, @ParameterObject ShopDivisionReceiverGroup shopDivisionReceiverGroup) {
        if (Objects.isNull(shopDivisionReceiverGroup.getShopId())) {
            shopDivisionReceiverGroup.setShopId(SecurityUtils.getShopUser().getShopId());
        }
        IPage<ShopDivisionReceiverGroup> shopWalletLogPage = shopDivisionReceiverGroupService.pageByParam(page, shopDivisionReceiverGroup);
        return ServerResponseEntity.success(shopWalletLogPage);
    }

    @Operation(summary = "账号组详情", description = "账号组详情")
    @GetMapping(value = "/{recordId}")
    public ServerResponseEntity<ShopDivisionReceiverGroup> detail(@PathVariable("recordId") Long recordId) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        ShopDivisionReceiverGroup record = shopDivisionReceiverGroupService.findByIdAndShopId(recordId, shopId);
        return ServerResponseEntity.success(record);
    }


    @Operation(summary = "新增分账账号组", description = "新增分账账号组")
    @PostMapping(value = "")
    @Parameters(value = {
            @Parameter(name = "receiverGroupName", description = "组名称"),
            @Parameter(name = "shopId", description = "店铺id"),
            @Parameter(name = "autoDivisionFlag", description = "自动分账组（当订单分账模式为自动分账，改组将完成分账逻辑） 0-否 1-是")})
    public ServerResponseEntity<Void> add(@RequestBody ShopDivisionReceiverGroup shopDivisionReceiverGroup) {
        shopDivisionReceiverGroup.setShopId(SecurityUtils.getShopUser().getShopId());
        shopDivisionReceiverGroup.setCreateTime(new Date());
        shopDivisionReceiverGroup.setUpdateTime(new Date());
        shopDivisionReceiverGroup.setCreatedBy(SecurityUtils.getShopUser().getUserId());
        shopDivisionReceiverGroupService.save(shopDivisionReceiverGroup);
        return ServerResponseEntity.success();
    }


    @Operation(summary = "更新分账账号组", description = "更新分账账号组")
    @Parameters({
            @Parameter(name = "recordId", description = "账号组ID", required = true),
            @Parameter(name = "autoDivisionFlag", description = "自动分账组（当订单分账模式为自动分账，改组将完成分账逻辑） 0-否 1-是", required = true),
            @Parameter(name = "receiverGroupName", description = "组名称", required = true)})
    @PutMapping(value = "/{recordId}")
    public ServerResponseEntity<Void> update(@PathVariable("recordId") Long recordId, @RequestBody ShopDivisionReceiverGroup shopDivisionReceiverGroup) {
        LambdaUpdateWrapper<ShopDivisionReceiverGroup> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ShopDivisionReceiverGroup::getReceiverGroupId, recordId);
        updateWrapper.eq(ShopDivisionReceiverGroup::getShopId, SecurityUtils.getShopUser().getShopId());
        shopDivisionReceiverGroup.setUpdateTime(new Date());
        if (shopDivisionReceiverGroupService.update(shopDivisionReceiverGroup, updateWrapper)) {
            //更新其他组为非默认分账组
            if (shopDivisionReceiverGroup.getAutoDivisionFlag() == 1) {
                shopDivisionReceiverGroupService.update(
                        new LambdaUpdateWrapper<ShopDivisionReceiverGroup>()
                                .set(ShopDivisionReceiverGroup::getAutoDivisionFlag, 0)
                                .eq(ShopDivisionReceiverGroup::getShopId, SecurityUtils.getShopUser().getShopId())
                                .ne(ShopDivisionReceiverGroup::getReceiverGroupId, recordId));
            }
        }
        return ServerResponseEntity.success();
    }

    @Operation(summary = "删除分账账号组", description = "删除分账账号组")
    @Parameters({@Parameter(name = "recordId", description = "账号组ID", required = true)})
    @DeleteMapping(value = "/{recordId}")
    public ServerResponseEntity<Void> del(@PathVariable("recordId") Long recordId) {
        ShopDivisionReceiverGroup record = shopDivisionReceiverGroupService.getOne(
                new LambdaQueryWrapper<ShopDivisionReceiverGroup>()
                        .eq(ShopDivisionReceiverGroup::getReceiverGroupId, recordId)
                        .eq(ShopDivisionReceiverGroup::getShopId, SecurityUtils.getShopUser().getShopId()));
        if (record == null) {
            throw new YamiShopBindException("记录不存在");
        }
        if (shopDivisionReceiverService.count(new LambdaQueryWrapper<ShopDivisionReceiver>().eq(ShopDivisionReceiver::getReceiverGroupId, recordId)) > 0) {
            throw new YamiShopBindException("该组存在账号，无法删除");
        }
        shopDivisionReceiverGroupService.removeById(recordId);
        return ServerResponseEntity.success();
    }


    @GetMapping("/allGroup")
    @Operation(summary = "查询店铺所有账号组", description = "查询店铺所有账号组")
    public ServerResponseEntity<List<ShopDivisionReceiverGroup>> getAllGroup() {
        List<ShopDivisionReceiverGroup> list = shopDivisionReceiverGroupService.list(
                new LambdaQueryWrapper<ShopDivisionReceiverGroup>()
                        .eq(ShopDivisionReceiverGroup::getShopId, SecurityUtils.getShopUser().getShopId())
                        .orderByDesc(ShopDivisionReceiverGroup::getCreateTime));
        return ServerResponseEntity.success(list);
    }

}
